<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\Controller;
use App\Models\LiveAdmin;
use App\Services\LiveService;
use App\Services\ConfigService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\Live;

class LiveController extends Controller
{
    //
    protected $user;

    public function push(Request $request)
    {
        //验证直播权限
        if (!access('live', false)) {
            return back()->with('danger', '请联系管理员开启直播');
        }
        $request->validate(['title' => ['required'], 'description' => ['required']]);
        //获取登录的用户信息
        $this->user = user()->make();
        //获取模块中的直播配置,
        $config = $this->createLiveConfig();

        //获取数据，如果不存在则在模型中新建
        $this->saveCurrentLiveConfig($config, $this->user);
        //进行直播前，清空所有的直播观众记录,
        //live_id规则为user的id
        LiveAdmin::where('live_id', $this->user->id)->where('site_id', site()['id'])->where('module_id', module()['id'])->delete();
        //创建通知监控
        $this->createNotify();
        return back()->with('success', '直播地址已生成');

    }

    protected function createNotify()
    {
        $liveService = app(LiveService::class);
        $config = app(ConfigService::class)->loadCurrentModuleConfig()['live'];
        //获取阿里云配置
        $aliyun = site()['config']['aliyun'];

        //通知配置
        $res = $liveService->notify(
            $aliyun['accessKeyId'],
            $aliyun['accessKeySecret'],
            $config['push_url'],
            route('common.live.notify')
        );
    }

    protected function createLiveConfig()
    {
        //实例化直播服务
        $liveService = app(LiveService::class);
        //实例化并载入模块配置,需要
        $config = app(ConfigService::class)->loadCurrentModuleConfig()['live'];

        $stream = Str::random(10);
        $app = $this->user->id . '_' . Str::random(4);
        //生产播流地址
        $playUrls = $liveService->playUrl($config['play_url'], $app, $stream, $config['play_key']);
        //生产推流地址
        $pushUrl = $liveService->pushUrl($config['push_url'], $app, $stream, $config['push_key']);
        return ['play' => $playUrls, 'push' => $pushUrl, 'is_live' => false];
    }

    public function saveCurrentLiveConfig($config, $user)
    {
        $config = $config + request()->input();

        $live = Live::firstOrNew(
            [
                'site_id' => site()['id'],
                'module_id' => module()['id'],
                'user_id' => $user['id']
            ],
            [
                'config' => $config
            ]
        );
        //更新config配置项，title,description,preview,playUrl,pushUrl,
        $live->config = array_merge($live->config, $config);
        $live->save();
    }

    public function loadCurrentLiveConfig()
    {
        return Live::where('site_id', site()['id'])->where('user_id', user()['id'])->where('module_id', module()['id'])->config;
    }

    //接收阿里云通知，改变直播状态，如开播或停播
    public function notify(Request $request)
    {
        switch ($request->input('action')) {
            case "publish":
                $this->saveCurrentModuleConfig(['is_live' => true]);
                break;

            case 'publish_done':
                $this->saveCurrentModuleConfig(['is_live' => false]);
                break;
        }
    }
}
